import { MiddlerCode, Middleware, Middler } from ".";

function sleep(ms: number) {
  return new Promise((r) => {
    setTimeout(r, ms);
  });
}

const mockSum: MiddlerCode<MockRequestContext> = async function (ctx) {
  await sleep(1000);
  ctx.res = {
    code: 200,
    body: ctx.req.a + ctx.req.b,
  };
};

const test1: Middleware<MockRequestContext> = async function (ctx, next) {
  console.log("test1 begin", ctx.req);
  ctx.req.a += 1;
  await next();
  ctx.res.body += 1;
  console.log("test1 end", ctx.res);
};

const test2: Middleware<MockRequestContext> = async function (ctx, next) {
  console.log("test2 begin", ctx.req);
  ctx.req.a += 1;
  await next();
  ctx.res.body += 1;
  console.log("test2 end", ctx.res);
};

const test3: Middleware<MockRequestContext> = async function (ctx, next) {
  console.log("test3 begin", ctx.req);
  ctx.req.a += 1;
  await next();
  ctx.res.body += 1;
  console.log("test3 end", ctx.res);
};

interface MockRequestContext {
  req: any;
  res: { code: number; body: any };
}

const middler = new Middler<MockRequestContext>([test1]);

middler.use(test2, test3);

async function sum() {
  console.log("sum begin");
  const ctx = { req: { a: 1, b: 1 }, res: null }
  await middler.exec(ctx, mockSum);
  console.log("sum result:", ctx.res);
}

sum();
